<template>
	<div class="app-container">
		<!-- 高级查询 -->
		<el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
			<el-form-item label="客户代码：" prop="customerNo">
			<!-- 	<el-input v-model="queryParams.customerNo" class="filter-item">
					<i slot="suffix" class="el-input__icon el-icon-search" @click="openFromSelector" />
				</el-input>
				<customer-selector :visible.sync="fromSelectorVisible" @selected="handleFromSelected" />
		 -->
       <el-select  v-model="queryParams.customerNo"
      style="width: 100%" filterable clearable
      	placeholder="请选择客户" >
      	<el-option v-for="option in options.customerOptions" :key="option.id"
      		:label="option.customerName" :value="option.id" />
      </el-select>
     </el-form-item>
			<!-- <el-form-item label="">
				<el-input v-model="queryParams.customerName" size="small" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
			</el-form-item> -->

			<el-form-item>
				<el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<!-- 工具栏 -->
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button v-hasPermission="['pms:tWhWarehouseCustomerMaterial:insert']" type="primary"
					icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button v-hasPermission="['pms:tWhWarehouseCustomerMaterial:update']" type="success"
					icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button v-hasPermission="['pms:tWhWarehouseCustomerMaterial:delete']" type="danger"
					icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>
			</el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['pms:tWhWarehouseCustomerMaterial:import']" type="info"
        icon="el-icon-upload2" size="mini" @click="openUploadDialog">批量导入</el-button>
      </el-col>
			<el-col :span="1.5">
				<el-button v-hasPermission="['pms:tWhWarehouseCustomerMaterial:export']" type="warning"
					icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
			</el-col>
			<right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
		</el-row>

		<!-- 数据列表 -->
		<el-table v-loading="loading" :data="page.records" highlight-current-row
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<!-- <el-table-column label="" align="center" prop="customerNo" />
      <el-table-column label="" align="center" prop="materialNo" />
      <el-table-column label="" align="center" prop="measUnitNo" />
      <el-table-column label="" align="center" prop="conversionCoefficient" />
      <el-table-column label="" align="center" prop="isActived" />
      <el-table-column label="" align="center" prop="remark" />
      <el-table-column label="" align="center" prop="version" />
      <el-table-column label="" align="center" prop="siteCode" />
      <el-table-column label="" align="center" prop="receiptType" />
      <el-table-column label="" align="center" prop="accountingType" />
      <el-table-column label="" align="center" prop="allowZeroCost" />
      <el-table-column label="" align="center" prop="checkerId" />
      <el-table-column label="" align="center" prop="price" />
      <el-table-column label="" align="center" prop="convertQuantity" />
      <el-table-column label="" align="center" prop="feeYn" />
      <el-table-column label="" align="center" prop="lowestQuantity" />
      <el-table-column label="" align="center" prop="unitPrice" />
      <el-table-column label="" align="center" prop="truckFee" />
      <el-table-column label="" align="center" prop="qaDate" />
      <el-table-column label="" align="center" prop="feeUnitNo" />
      <el-table-column label="" align="center" prop="customerId" /> -->
			<el-table-column label="客户名称" align="center" prop="customerName" />
			<el-table-column label="客户编码" align="center" prop="customerNo" />
			<el-table-column label="物料名称" align="center" prop="skuName" />
			<el-table-column label="物料编码" align="center" prop="materialNo" />
			<el-table-column label="单位" align="center" prop="measUnitNo" />
			<el-table-column label="二维码" align="center" prop="createTime" width="400">
			    <template slot-scope="scope">
			     <div :id="'qrCode-' + scope.$index">
			      <!-- {{scope.$index}} -->
			      <vue-qr
			       :text="scope.row.customerName + '-' + scope.row.customerNo + '-' + scope.row.skuName + '-' + scope.row.materialNo+ '-' + scope.row.shipByPackOrqty+ '-' + scope.row.spec+ '-' + scope.row.skuCode"
			       :size="200"></vue-qr>
				    <div>{{'公司名称：'+scope.row.customerName}}</div>
					<!-- <div>{{'客户编码：'+scope.row.customerNo}}</div> -->
					<div>{{'货物名称：'+scope.row.skuName}}</div>
					<div>{{'货物编码：'+scope.row.skuCode}}</div>
					<!-- <div>{{'结算依据：'+scope.row.shipByPackOrqty}}</div> -->
				<!-- 	<div>{{'货物规格：'+scope.row.spec}}</div> -->
					<div>{{'图号：'+scope.row.skuCode}}</div>
			     </div>

			    </template>
			   </el-table-column>
			<el-table-column label="记录 ID，系统自动产生" width="180" align="center" prop="id" />
			<el-table-column label="创建时间" align="center" prop="createDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="更新时间" align="center" prop="updateDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.updateDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
				<template slot-scope="scope">

						<el-button size="small"  type="primary"  icon="el-icon-plus" @click="handlePrint(scope.$index)">打印</el-button>
					<el-button v-hasPermission="['pms:tWhWarehouseCustomerMaterial:delete']" size="mini" type="text"
						icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
            <el-button v-hasPermission="['pms:tWhWarehouseCustomerMaterial:update']" size="mini" type="text"
            	icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize"
			@pagination="handleQuery" />
<el-dialog :title="uploadDialog.title" :visible.sync="uploadDialog.visible" width="400px" append-to-body>
      <div v-loading="uploadLoading">
        <el-upload
          ref="upload"
          :limit="1"
          :headers="uploadData.headers"
          :action="uploadData.url + '?updateSupport=' + uploadData.updateSupport"
          :data="uploadData.params"
          :disabled="uploadData.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          accept=".xlsx, .xls"
          drag
        >
        <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>

             <div slot="tip" class="el-upload__tip">
                <el-link type="info" style="font-size:16px" @click="handleDownloadTemplate">下载模板</el-link>
              </div>

              <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="confirmUploadDialog">确 定</el-button>
              <el-button @click="resetUploadDialog">取 消</el-button>
            </div>
          </div>
        </el-dialog>
		<!-- 添加/修改对话框 -->
		<el-dialog :title="tWhWarehouseCustomerMaterialFormDialog.title"
			:visible.sync="tWhWarehouseCustomerMaterialFormDialog.visible" :close-on-click-modal="false"
			:before-close="resetTWhWarehouseCustomerMaterialFormDialog" width="500px" append-to-body>
			<el-form ref="tWhWarehouseCustomerMaterialForm" :model="tWhWarehouseCustomerMaterialFormData"
				:rules="tWhWarehouseCustomerMaterialFormRules" label-width="80px">
				<el-form-item label="" prop="customerNo">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.customerNo" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="materialNo">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.materialNo" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="measUnitNo">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.measUnitNo" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="conversionCoefficient">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.conversionCoefficient" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="isActived">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.isActived" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="remark">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.remark" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="version">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.version" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="siteCode">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.siteCode" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="allowZeroCost">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.allowZeroCost" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="checkerId">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.checkerId" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="price">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.price" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="convertQuantity">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.convertQuantity" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="feeYn">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.feeYn" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="lowestQuantity">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.lowestQuantity" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="unitPrice">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.unitPrice" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="truckFee">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.truckFee" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="qaDate">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.qaDate" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="feeUnitNo">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.feeUnitNo" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="" prop="customerId">
					<el-input v-model="tWhWarehouseCustomerMaterialFormData.customerId" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="创建时间" prop="createDate">
					<el-date-picker v-model="tWhWarehouseCustomerMaterialFormData.createDate" type="date"
						value-format="yyyy-MM-dd" size="small" style="width: 100%" placeholder="选择创建时间" clearable />
				</el-form-item>
				<el-form-item label="更新时间" prop="updateDate">
					<el-date-picker v-model="tWhWarehouseCustomerMaterialFormData.updateDate" type="date"
						value-format="yyyy-MM-dd" size="small" style="width: 100%" placeholder="选择更新时间" clearable />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="confirmTWhWarehouseCustomerMaterialFormDialog">确 定</el-button>
				<el-button @click="resetTWhWarehouseCustomerMaterialFormDialog">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import TWhWarehouseCustomerMaterialApi from '@/api/pms/TWhWarehouseCustomerMaterialApi'
	import CustomerSelector from '@/views/basic/customer/CustomerSelector'
  import CustomerApi from '@/api/basic/CustomerApi';
  import AuthUtils from '@/utils/AuthUtils'
	import vueQr from 'vue-qr'
	import printJS from 'print-js'
	const defaultTWhWarehouseCustomerMaterialFormData = {
		customerNo: null,
		materialNo: null,
		measUnitNo: null,
		conversionCoefficient: null,
		isActived: null,
		version: null,
		siteCode: null,
		receiptType: null,
		accountingType: null,
		allowZeroCost: null,
		checkerId: null,
		price: null,
		convertQuantity: null,
		feeYn: null,
		lowestQuantity: null,
		unitPrice: null,
		truckFee: null,
		qaDate: null,
		feeUnitNo: null,
		customerId: null,
		createDate: null,
		updateDate: null

	}
	export default {
		name: 'TWhWarehouseCustomerMaterialList',
		components:{
			vueQr
		},
		data() {
			return {
				options: {
					sysYnTypeOptions: this.$constant.sysYnTypeOptions,
          customerOptions:[],
				},
				queryParams: {
					customerNo: null,
					materialNo: null,
					measUnitNo: null,
					conversionCoefficient: null,
					isActived: null,
					remark: null,
					version: null,
					siteCode: null,
					receiptType: null,
					accountingType: null,
					allowZeroCost: null,
					checkerId: null,
					price: null,
					convertQuantity: null,
					feeYn: null,
					lowestQuantity: null,
					unitPrice: null,
					truckFee: null,
					qaDate: null,
					feeUnitNo: null,
					customerId: null,
					createDate: null,
					updateDate: null,
					isValid: this.$constant.Y
				},
				page: {
					current: 1,
					pageSize: 10,
					total: 0,
					records: []
				},
				tWhWarehouseCustomerMaterialFormDialog: {
					title: '',
					visible: false
				},
				tWhWarehouseCustomerMaterialFormData: Object.assign({}, defaultTWhWarehouseCustomerMaterialFormData),
				tWhWarehouseCustomerMaterialFormRules: {
					customerNo: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],

					materialNo: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],

					measUnitNo: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],

					conversionCoefficient: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],

					isActived: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],

					version: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],

					siteCode: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],

					receiptType: [{
						required: true,
						message: '不能为空',
						trigger: 'change'
					}],

					price: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}],

					createDate: [{
						required: true,
						message: '创建时间不能为空',
						trigger: 'blur'
					}],

					updateDate: [{
						required: true,
						message: '更新时间不能为空',
						trigger: 'blur'
					}]

				},
        uploadDialog: {
          title: '订单批量导入',
          visible: false
        },
        uploadData: {
          headers: { Authorization: 'Bearer ' + AuthUtils.getToken() }, // 上传请求头
          url: process.env.VUE_APP_BASE_API + '/basic/customer/importCustomerMaterialData', // 上传的地址
         // params: {
         //   customerNo: '1353968310689075200' // 会员商城
        //  },
          isUploading: false, // 是否禁用上传
          updateSupport: 0 // 是否更新已经存在的数据
        },
				loading: true,
				searchVisible: true,
        fromSelectorVisible: false,
				multipleSelection: [],
        uploadLoading: false,
				isSingle: true,
				isMultiple: true
			}
		},
		created() {
			this.handleQuery()
			this.loadOptions()
		},
		methods: {
			loadOptions() {
        let that = this;
       
        CustomerApi.list().then(res => {
        	that.options.customerOptions = res.data
        
        })
      },
			handlePrint(index) {
				console.log(index)
				let userAgent = navigator.userAgent;
				let printableId = 'qrCode-' + index;
				console.log(printableId)
				//判断是否Firefox浏览器
				if (userAgent.indexOf("Firefox") > -1) {
					console.log('Firefox')
					printJS({
						printable: printableId, // 标签元素id
						type: 'html',
						header: '',
						style: `@page {size:auto;margin-top:100px; margin-left:15px; margin-right: 15px;}
			            thead th {
			              border-top: 1px solid #000;
			              border-right: 1px solid #000;
			              border-left: 1px solid #000;
			            }
			            tbody td {
			              border: 1px solid #000;
			            }
			            tbody {
			              text-align: center;
			            }
			            table {
			              border-collapse: collapse;
			            }`,
					});
				}
				//判断是否chorme浏览器
				if (userAgent.indexOf("Chrome") > -1) {
					console.log('Chrome')
					printJS({
						printable: printableId, // 标签元素id
						type: 'html',
						header: '',
						documentTitle: '',
						style: `@page {margin-left:50%;font-size: 2px;}
			            thead th {
			              border-top: 1px solid #000;
			              border-right: 1px solid #000;
			              border-left: 1px solid #000;
			            }
			            tbody td {
			              border: 1px solid #000;
			            }
			            tbody {
			              text-align: center;
			            }
			            table {
			              border-collapse: collapse;
			            }`,
					});
				}
				//判断是否IE浏览器
				if (!!window.ActiveXObject || "ActiveXObject" in window) {
					console.log('IE')
					printJS({
						printable: printableId, // 标签元素id
						type: 'html',
						header: '',
						style: `@page {size:auto;margin-top:100px; margin-left:15px; margin-right: 15px;}
			            thead th {
			              border-top: 1px solid #000;
			              border-right: 1px solid #000;
			              border-left: 1px solid #000;
			            }
			            tbody td {
			              border: 1px solid #000;
			            }
			            tbody {
			              text-align: center;
			            }
			            table {
			              border-collapse: collapse;
			            }`,
					});
				}
			},
			handleAdd() {
				this.openTWhWarehouseCustomerMaterialFormDialog()
			},
			openFromSelector() {
				this.fromSelectorVisible = true
			},
			handleFromSelected(obj) {
				console.log(obj)

				this.queryParams.customerNo = obj.id
				this.queryParams.customerName = obj.customerName


			},
      openUploadDialog() {
        this.resetUploadDialog()
        this.uploadDialog.visible = true
      },
      confirmUploadDialog() {

          this.uploadLoading = true
          this.$refs.upload.submit()

      },
      resetUploadDialog() {
        this.uploadDialog.visible = false

      },
      handleFileUploadProgress(event, file, fileList) {
        this.uploadData.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.uploadLoading = false
        this.uploadDialog.visible = false
        this.uploadData.isUploading = false
        this.$refs.upload.clearFiles()
        this.$alert(response.data ? response.data : response.msg, '导入结果', { dangerouslyUseHTMLString: true })
        this.queryParams.status = null
        this.handleQuery()
      },
      // 文件上传失败处理
      handleFileError(response, file, fileList) {
        this.uploadLoading = false
      },
      handleDownloadTemplate() {
        TWhWarehouseCustomerMaterialApi.importTemplate().then(response => {
          this.$common.download(response.data)
        })
      },
			handleRemove(row) {
				const ids = row.id || this.multipleSelection.map(item => item.id)
				this.$confirm('是否确认删除数据?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function() {
					return TWhWarehouseCustomerMaterialApi.remove(ids)
				}).then(() => {
					this.handleQuery()
					this.$message.success('删除成功')
				})
			},
			handleEdit(row) {
				const id = row.id || this.multipleSelection.map(item => item.id)[0]
				this.openTWhWarehouseCustomerMaterialFormDialog(id)
			},
			handleQuery() {
				this.loading = true
				TWhWarehouseCustomerMaterialApi.page(this.queryParams, this.page).then(response => {
					this.page.records = response.data.records
					this.page.total = response.data.total
					this.loading = false
				}, () => {
					this.loading = false
				})
			},
			handleExport() {
				this.$confirm('是否确认导出数据?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function() {
					return TWhWarehouseCustomerMaterialApi.exportData(this.queryParams)
				}).then(response => {
					this.$common.download(response.msg)
				})
			},
			openTWhWarehouseCustomerMaterialFormDialog(id) {
				this.tWhWarehouseCustomerMaterialFormDialog.visible = true
				if (id) {
					this.tWhWarehouseCustomerMaterialFormDialog.title = '共享仓储客户物料-修改'
					TWhWarehouseCustomerMaterialApi.get(id).then(response => {
						this.tWhWarehouseCustomerMaterialFormData = {
							...this.tWhWarehouseCustomerMaterialFormData,
							...response.data
						}
					})
				} else {
					this.tWhWarehouseCustomerMaterialFormDialog.title = '共享仓储客户物料-添加'
				}
			},
			confirmTWhWarehouseCustomerMaterialFormDialog() {
				this.$refs['tWhWarehouseCustomerMaterialForm'].validate(valid => {
					if (valid) {
						if (this.tWhWarehouseCustomerMaterialFormData.id) {
							TWhWarehouseCustomerMaterialApi.edit(this.tWhWarehouseCustomerMaterialFormData).then(
								response => {
									this.$message.success('修改成功')
									this.resetTWhWarehouseCustomerMaterialFormDialog()
									this.handleQuery()
								})
						} else {
							TWhWarehouseCustomerMaterialApi.add(this.tWhWarehouseCustomerMaterialFormData).then(
								response => {
									this.$message.success('添加成功')
									this.resetTWhWarehouseCustomerMaterialFormDialog()
									this.handleQuery()
								})
						}
					}
				})
			},
			resetTWhWarehouseCustomerMaterialFormDialog() {
				this.tWhWarehouseCustomerMaterialFormDialog = {
					title: '',
					visible: false
				}
				this.tWhWarehouseCustomerMaterialFormData = Object.assign({}, defaultTWhWarehouseCustomerMaterialFormData)
				this.resetForm('tWhWarehouseCustomerMaterialForm')
			},
			handleSelectionChange(selection) {
				this.multipleSelection = selection
				this.isSingle = selection.length !== 1
				this.isMultiple = !selection.length
			},
			resetQuery() {
				this.page.current = 1
				this.resetForm('queryForm')
				this.handleQuery()
			}
		}
	}
</script>
